var intervalTime = 3000; //  time repeat
// init all data
var DEFAULT_X_AXES = 
[{
    gridLines : {display : false}
}]


var DEFAULT_BAR_CHART_OPTIONS = 
{
    // Elements options apply to all of the options unless overridden in a dataset
    // In this case, we are setting the border of each bar to be 2px wide and green
    elements: 
    {
        rectangle: 
        {
            borderWidth: 1,
            //borderColor: 'rgb(0, 255, 0)'
            //borderSkipped: 'bottom'
        }
    },
    responsive: true,
    legend: 
    {
        display: false,
        position: 'bottom',
    },

    barPercentage: 0.5,
    categoryPercentage: 0.2,
    scales: {
        xAxes : DEFAULT_X_AXES,
        yAxes: 
        [
            {
                display: true,
                ticks: 
                {
                    suggestedMin: 0, 
                    suggestedMax: 100,   // minimum will be 0, unless there is a lower value.
                    // OR //
                    stepSize: 5,
                    beginAtZero: true   // minimum value will be 0.
                }
            }
        ]
    }
};



var DEFAULT_LINE_CHART_OPTIONS = 
{
    tooltips: 
    { mode: 'x-axis'},
    scales: 
    {   
        xAxes : DEFAULT_X_AXES,
        yAxes: 
        [
            {
                display: true,
                scaleLabel: {
                    display: false,
                },
                ticks: {
                    suggestedMin: 0,
                    stepSize: 5,
                    suggestedMax: 50,
                }
            }
        ]
    }       
};

var _7_backgroudColors = 
[
    '#f44336',
    '#e91e63',
    '#9c27b0',
    '#673ab7',
    '#3f51b5',
    '#2196F3',
    '#87CEEB',
    '#00bcd4',
    '#00ffff',
    '#009688',
    '#4CAF50',
    '#8bc34a',
    '#cddc39',
    '#fdf5e6',
    '#f0e68c',
    '#ffeb3b',
    '#ffc107'
];

var REPORT_ALL_DATA_KEY = [
    {
        id:'inboundNum',
        label:'呼入量',
        unit:'',
    },
    {
        id:'acdCallsNum',
        label:'转人工量',
        unit:'',
    },
    {
        id:'ansAcdCallNum',
        label:'人工接通量',
        unit:'',
    },
    {
        id:'abnAcdCallNum',
        label:'排队放弃量',
        unit:'',
    },
    {
        id:'acdAnsRate',
        label:'排队接通率',
        unit:'%',
    },
    {
        id:'serviceLevel_20',
        label:'服务水平',
        unit:'%',
    },
    {
        id:'outboundNum',
        label:'呼出量',
        unit:'',
    },
    {
        id:'avgInqueueTimeLen',
        label:'平均排队时长',
        unit:'s',
    },
    {
        id:'maxInqTimeLen',
        label:'最大排队时长',
        unit:'s',
    },
    {
        id:'avgTalkingTimeLen',
        label:'平均通话时长',
        unit:'s',
    },
    {
        id:'avgRingTimeLen',
        label:'平均振铃时长',
        unit:'s',
    },
    {
        id:'abnRingNum',
        label:'振铃放弃量',
        unit:'',
    },
    {
        id:'ivrAbnTotal',
        label:'IVR放弃量',
        unit:'',
    },
    {
        id:'abnRate',
        label:'放弃率',
        unit:'%',
    },
    {
        id:'acdRate',
        label:'IVR转接率',
        unit:'%',
    },
]

var LIVE_ALL_DATA_KEY = [
    {
        id:'ContactInbound',
        label:'当前呼入数',
        unit:'',
    },
    {
        id:'ContactInQueue',
        label:'当前排队数',
        unit:'',
    },
    {
        id:'InboundConnect',
        label:'呼入通话数',
        unit:'',
    },
    {
        id:'OutboundConnect',
        label:'呼出通话数',
        unit:'',
    },
    {
        id:'AgentTotal',
        label:'签入人数',
        unit:'',
    },
    {
        id:'AgentNotReady',
        label:'置忙人数',
        unit:'',
    },
    {
        id:'AgentReady',
        label:'空闲人数',
        unit:'',
    },
    {
        id:'AgentAfterCallWork',
        label:'整理人数',
        unit:'',
    },
    {
        id:'AgentOtherWork',
        label:'休息人数',
        unit:'',
    },
    {
        id:'AgentTalking',
        label:'通话人数',
        unit:'',
    },
    {
        id:'AgentOtherstatus',
        label:'其他人数',
        unit:'',
    },
]

function errorLog(xhr,status,error) {
    console.log("xhr:"+xhr);
    console.log("status:"+status);
    console.log("error:"+error);
}


// url is a http url, hander is a function,with a result
function callAsynWithHandler(url,handler) {
    $.ajax(
        {
            timeout: intervalTime,
            url: url,
            success: handler,
            error: errorLog
        }
    );
}


// init data use this function to 
// uiupdate is a function for update the ui with the data
function initData(url1,url2,url3,url4,filterNoUrl,filterDataUrl,uiupdate){
    callAsynWithHandler(url1,function (result1) { 
        window.mServiceno = result1;
        callAsynWithHandler(url2,function (result2) {
            window.mLiveData = result2;
            callAsynWithHandler(url3,function (result3) {
                window.mReportData = result3;
                callAsynWithHandler(url4,function(result4){
                    window.mTimerData = result4;
                    callAsynWithHandler(filterNoUrl,function(filter){
                        window.mNumFilter = filter;
                        callAsynWithHandler(filterDataUrl,function (filterData){
                            window.mDataFilter = filterData;
                            firstUpdateDataUi(uiupdate);
                        })
                        
                    });
                });
            });
        });
    });
}

function firstUpdateDataUi(handler) {
    updateDataUi('all');
    setCustomDataUi(window.mDataFilter);
    setCustomNumUi(window.mNumFilter);
    // num
    insertConfigNumElement("#config-num-items",window.mServiceno,window.mNumFilter);
    // data 
    insertConfigElement("#config-data_items",null,window.mDataFilter);
    handler();
}

// start update the ui interval
function repeatLiveData(url) {
    setInterval(function() {
        $.ajax({
            timeout: intervalTime,
            url: url, // todo
            success: function(result) {
                window.mLiveData = result;
                updateDataUi(undefined);
            },
            error: errorLog
        })
    },3000);
}

// key is the num
function updateDataUi(key) {
    if(key) {
        window.mCurKey = key;
    }
    var data_serviceno = window.mServiceno;
    var data_live = window.mLiveData['data'][window.mCurKey];
    var data_report = window.mReportData['data'][window.mCurKey]['statData'];

    // update key;
    setKeyLabel(null,window.mCurKey);
    setData(data_live,'ul#live-core-ui>li>span[data-id]');
    setData(data_report,'ul#report-core-ui>li>span[data-id]');
    setChartLive('#_chart',data_live);
    setData(data_live,'#custom-live-ui>div[data-id]')
    setData(data_report,'#custom-report-ui>div[data-id]')
    setProgressData(data_report);
    setChartTimes('#_chart2');
}

function setKeyLabel(selector,key){
  // todo
}

function setCustomDataUi(filter) {
    $("#custom-report-ui>div").each(function () {
        if($.inArray($(this).data('id'),filter) > -1){
            $(this).show();
        }else {
            $(this).hide();
        }
    })
    $('#custom-live-ui>div').each(function() {
        if($.inArray($(this).data('id'),filter) > -1){
            $(this).show();
        }else {
            $(this).hide();
        }
    });
}

function saveCustomData() {
    w3_loading();
    var data = "userId="+readCookie('userId');
    var i = 0;
    $('#config-data_items>div').each(function() {
        var $item = $(this);
        var $firstElement = $item.children(':first');
        var myText = $firstElement.text();
        if(myText.indexOf('outline') < 0) {
            var data_id = $item.data('id');
            data += "&dataIndex["+i+"]="+data_id;
            i++;
        }
    });
    $.ajax({url : "/customization/array/dataIndex",
	data : data,
	type : "PUT",
	success : function(result){
           if(checkSaveResult(result)) {
                window.mDataFilter = result['customizations']['dataIndex'];
                setCustomDataUi(window.mDataFilter);
           }else {
                // todo;
           }
           w3_loaded()
        },
    error:function (xhr,status,error) {
        //todo
        w3_loaded()
    }
    });
}

function setCustomNumUi(filter) {
    var $menu = $('#demo');
    $menu.empty();
    $menu.append("<a data-id=\"all\" href=\"javascript:void(0)\">全部</a>");
    if(filter) {
        for(var i = 0; i < filter.length; i++) {
            $menu.append("<a data-id=\""+filter[i]+"\" href=\"javascript:void(0)\">"+filter[i]+"</a>");
        }
    }
    $("#demo > a").unbind("click").click(function(e){
            window.mCurKey = $(this).data('id');
            updateDataUi(window.mCurKey);
            
            e.preventDefault();
    });
}

function saveCustomNum() {
    w3_loading();
    var data = "userId="+readCookie('userId');
    var i = 0;
    $('#config-num-items>div').each(function() {
        var $item = $(this);
        var $firstElement = $item.children(':first');
        var myText = $firstElement.text();
        if(myText.indexOf('outline') < 0) {
            data += "&serviceNo["+i+"]="+$item.data('id');
            i++;
        }
    });
    $.ajax({url : "/customization/array/serviceNo",
	data : data,
	type : "PUT",
	success : function(result){
           if(checkSaveResult(result)) {
                window.mNumFilter = result['customizations']['serviceNo'];
                setCustomNumUi(window.mNumFilter);
           }else {
                // todo;
           }
           w3_loaded()
        },
    error:function (xhr,status,error) {
        //todo
        w3_loaded()
    }});
}

function checkSaveResult(result) {
    if(result['userId'] && result['customizations'] ) {
        return true;
    }else {
        return false;
    }
} 

function resetCheckBox(selector) {
    $("#"+selector+">div").each(function() {
        var $iconChild = $(this).children("i");
        var $textChild = $iconChild.next();

        if($iconChild.hasClass("w3-text-blue")) {
            $iconChild.removeClass("w3-text-blue");
            $iconChild.text('check_box_outline_blank')
            $textChild.removeClass("w3-text-teal");
        }
    });
}

function setProgressData(data) {
    $('#acdAnsRate').css('width', data['acdAnsRate']+'%');
    $('#acdAnsRate>div').text(data['acdAnsRate']+'%');

    $('#serviceLevel_20').css('width', data['serviceLevel_20']+'%');
    $('#serviceLevel_20>div').text(data['serviceLevel_20']+'%');
}

function setData(data,selector) {
    $(selector).each(function(){
        var item = $(this);
        var key = item.data("id");
        var unit = item.data("unit");
        var value = data[key];
        var selector = item.data('selector')
        var $html;
        if (selector) {
            $html = item.find(item.data('selector'));
        }else {
            $html = item;
        }
        if(value == "" || value === undefined ) {
            value = "0";
        }
        if(unit){
            $html.text(value+unit);
        }else {
            $html.text(value);
        }
    });
}

// 柱状图 标签 
var LIVE_KEY_LABEL = 
[
    ["AgentTotal","签入人数"],
    ["AgentAfterCallWork","整理人数"],
    ["AgentNotReady","置忙人数"],
    ["AgentOtherWork","休息人数"],
    ["AgentReady","空闲人数"],
    ["AgentTalking","通话人数"],
    ["AgentOtherstatus","其他人数"],           
];
// set bar chart
function setChartLive(selector,data) {
    var barDataSets = 
            [ 
                data[LIVE_KEY_LABEL[0][0]], 
                data[LIVE_KEY_LABEL[1][0]], 
                data[LIVE_KEY_LABEL[2][0]], 
                data[LIVE_KEY_LABEL[3][0]], 
                data[LIVE_KEY_LABEL[4][0]], 
                data[LIVE_KEY_LABEL[5][0]], 
                data[LIVE_KEY_LABEL[6][0]]
            ];

    if(window.mBar) {
        window.myBar.data.datasets[0] = barDataSets;
        window.myBar.update();
    }else {
        var barDataSets = 
    {
        labels: 
        [
            LIVE_KEY_LABEL[0][1],
            LIVE_KEY_LABEL[1][1],
            LIVE_KEY_LABEL[2][1],
            LIVE_KEY_LABEL[3][1],
            LIVE_KEY_LABEL[4][1],
            LIVE_KEY_LABEL[5][1],
            LIVE_KEY_LABEL[6][1]
        ],
        datasets:
        [{
            label: '监控',
            backgroundColor: 
            [
                _7_backgroudColors[0],
                _7_backgroudColors[1],
                _7_backgroudColors[2],
                _7_backgroudColors[3],
                _7_backgroudColors[4],
                _7_backgroudColors[5],
                _7_backgroudColors[6],
            ],
            data:
            [ 
                data[LIVE_KEY_LABEL[0][0]], 
                data[LIVE_KEY_LABEL[1][0]], 
                data[LIVE_KEY_LABEL[2][0]], 
                data[LIVE_KEY_LABEL[3][0]], 
                data[LIVE_KEY_LABEL[4][0]], 
                data[LIVE_KEY_LABEL[5][0]], 
                data[LIVE_KEY_LABEL[6][0]]
            ]
        }],
    }
        var ctxBar = $(selector)[0].getContext("2d")
        window.myBar = new Chart(
            ctxBar,
            {
                type: 'bar',
                data: barDataSets,
                options:DEFAULT_BAR_CHART_OPTIONS
            }
        );
    }
}

// set line chart
function setChartTimes(selector) {
        var timeRanges = window.mTimerData["timeRanges"]; //array
        var dataArrays = window.mTimerData["data"];// array;

        var inboundNums = {};//呼入量
        var acdCallsNums = {};//转人工量
        var ansAcdCallNums = {}; // 人工接通量
        var outboundNums = {};// 呼出量 
        var maxTime = timeRanges[0]; 

        for (var index in dataArrays){
            if (dataArrays[index]['timeRange'] > maxTime) {
                maxTime = dataArrays[index]['timeRange'];
            }
        }

        var maxIndex = $.inArray(maxTime,timeRanges) + 1;

        // // init the data arrays 
        for(var i = 0; i< maxIndex;i++){
            acdCallsNums[timeRanges[i]] = 0;
            inboundNums[timeRanges[i]] = 0;
            ansAcdCallNums[timeRanges[i]]=0;
            outboundNums[timeRanges[i]]=0;
        }

        // then filter the data 
        for(var i = 0; i < dataArrays.length;i++){
            var item = dataArrays[i];
            if(item["serviceNo"] == window.mCurKey){
                var timeRangeItem = item["timeRange"];
                if(timeRangeItem && timeRangeItem != ""){
                    inboundNums[timeRangeItem] = item["inboundNum"];
                    acdCallsNums[timeRangeItem] = item["acdCallsNum"];
                    ansAcdCallNums[timeRangeItem] = item["ansAcdCallNum"];
                    outboundNums[timeRangeItem] = item["outboundNum"];
                }
            }
        }

        var dataSetWithLabels = {
            labels: timeRanges,
            datasets:[
                {
                    label:"呼入量",
                    fill: false,
                    lineTension: 0.1,
                    borderWidth: 3,
                    borderColor: "rgba(220,20,60,1)",
                    backgroundColor: "rgba(220,20,60,1)",
                    data:formatTimerDatas(timeRanges,inboundNums)
                },
                {
                    label:"呼出量",
                    fill: false,
                    lineTension: 0.1,
                    borderWidth: 3,
                    borderColor: "rgba(139,0,139,1)",
                    backgroundColor: "rgba(139,0,139,1)",
                    data:formatTimerDatas(timeRanges,outboundNums)
                },
                {
                    label:"转人工量",
                    fill: false,
                    lineTension: 0.1,
                    borderWidth: 3,
                    borderColor: "rgba(72,61,139,1)",
                    backgroundColor: "rgba(72,61,139,1)",
                    data:formatTimerDatas(timeRanges,acdCallsNums)
                },
                {
                    label:"人工接通量",
                    fill: false,
                    lineTension: 0.1,
                    borderWidth: 3,
                    borderColor: "rgba(65,105,225,1)",
                    backgroundColor: "rgba(65,105,225,1)",
                    data:formatTimerDatas(timeRanges,ansAcdCallNums)
                }
            ]
        };

        if(window.myLine) {
            window.myLine.data.datasets = dataSetWithLabels.datasets;
            window.myLine.update();
        }else {
            var ctxLine = $(selector)[0].getContext("2d")
            window.myLine = new Chart(ctxLine, {
                    type: 'line',
                    data: dataSetWithLabels,
                    options: DEFAULT_LINE_CHART_OPTIONS
                });
        }
}

function formatTimerDatas(keyArray,mapData){
        var ar = new Array();
        for (var i = 0 ; i< keyArray.length;i++){
            var value = mapData[keyArray[i]];
            ar[i] = value;
        }
        return ar;
}


// ui  operations

// Open and close the sidenav on medium and small screens
function w3_open() {
    $('#mySidenav').css('display','block');
    $('#myOverlay').css('display','block');
    // document.getElementById("mySidenav").style.display = "block";
    // document.getElementById("myOverlay").style.display = "block";
}
function w3_close() {
    $('#mySidenav').css('display','none');
    $('#myOverlay').css('display','none');
}

function w3_loading() {
    $('#myLoading').css('display','block');
}

function w3_loaded() {
    $('#myLoading').css('display','none');
}

function createCheckBoxWithObject(dataObject){
    var unit = dataObject.unit;
    var id = dataObject.id;
    var label = dataObject.label;
    if(!id) {
        id = dataObject;
        label = id;
    }
    if(!unit) {
        unit = ""
    }
    
    return "<div data-unit=\""+unit +"\" data-id=\""+id+"\" class=\"w3-col s6 m3 w3-margin-top w3-margin-bottom\">\
    <i class=\"none-selection material-icons w3-left w3-text-blue\">\
      check_box\
    </i>\
    <label class=\"w3-validate w3-text-teal\">"+label+"</label>\
  </div>";
}

function createUnCheckBoxWithObject(dataObject){
    var unit = dataObject.unit;
    var id = dataObject.id;
    var label = dataObject.label;
    if(!id) {
        id = dataObject;
        label = id;
    }
    if(!unit) {
        unit = ""
    }
    return "<div data-unit=\""+unit +"\" data-id=\""+id+"\" class=\"w3-col s6 m3 w3-margin-top w3-margin-bottom\">\
      <i class=\"none-selection material-icons w3-left\">check_box_outline_blank</i>\
      <label class=\"w3-validate\">"+label+"</label>\
    </div>"
}

function insertConfigNumElement(selector_insert_point,allArrays,selectedArray) {
    var $config_data_item = $(selector_insert_point);
    $config_data_item.empty();
    for(var i = 0; i < allArrays.length; i++) {
        var key = allArrays[i];
        if($.inArray(key,selectedArray) != -1) {
            $config_data_item.append(createCheckBoxWithObject(allArrays[i]));
        }else {
            $config_data_item.append(createUnCheckBoxWithObject(allArrays[i]));
        } 
    }
    bindCheckBox(selector_insert_point);
}

// common method to insert element
function insertConfigElement(selector_insert_point,allArrays,selectedArray) {
    var $config_data_item = $(selector_insert_point);
    $config_data_item.empty();
    for(var i = 0; i < REPORT_ALL_DATA_KEY.length; i++) {
        var key = REPORT_ALL_DATA_KEY[i].id;
        if($.inArray(key,selectedArray) != -1) {
            $config_data_item.append(createCheckBoxWithObject(REPORT_ALL_DATA_KEY[i]));
        }else {
            $config_data_item.append(createUnCheckBoxWithObject(REPORT_ALL_DATA_KEY[i]));
        } 
    }
    for(var i = 0; i < LIVE_ALL_DATA_KEY.length; i++) {
        var key = LIVE_ALL_DATA_KEY[i].id;
        if($.inArray(key,selectedArray) != -1) {
            $config_data_item.append(createCheckBoxWithObject(LIVE_ALL_DATA_KEY[i]));
        }else {
            $config_data_item.append(createUnCheckBoxWithObject(LIVE_ALL_DATA_KEY[i]));
        }
    }
    bindCheckBox(selector_insert_point);
}

function bindCheckBox(selector) {
    $(selector+">div>i").unbind('click').bind('click',function (e){
        toggleCheckBox(this);
    });
}

//check box toggle
function toggleCheckBox(selector) {
    var $iconChild = $(selector);
    var $textChild = $iconChild.next();

    if($iconChild.hasClass("w3-text-blue")) {
        $iconChild.removeClass("w3-text-blue");
        $iconChild.text('check_box_outline_blank')
        $textChild.removeClass("w3-text-teal");
    }else {
        $iconChild.addClass("w3-text-blue");
        $iconChild.text('check_box')
        $textChild.addClass("w3-text-teal");
    }
}

// Change style of top container on scroll
window.onscroll = function() {myFunction()};
function myFunction() {
    var $myTop = $('#myTop');
    var $myIntro = $('#myIntro');
    if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
        $myTop.addClass('w3-card-4');
        $myIntro.addClass('w3-show-inline-block');
    } else {
        $myIntro.removeClass('w3-show-inline-block');
        $myTop.removeClass('w3-card-4');
    }
}

function scrollToElement(selector) {
  $('html,body').animate({
      scrollTop: $(selector).offset().top
  },400);
}

// Accordions
function myAccordion(id) {
    var $x = $('#'+id);
    var $prev = $x.prev();
    if($x.hasClass('w3-show')) {
      $x.removeClass('w3-show');
      $prev.removeClass('w3-theme');
    }else {
      $x.addClass('w3-show');
      $prev.addClass('w3-theme');
    }
}

// Cookies
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";               

    document.cookie = name + "=" + value + expires + "; path=/";
}
// to read userId use "readCookie("userId")"
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}